<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h1 class="title">
          <el-icon size="35"><MostlyCloudy /></el-icon>
          Visual协同
        </h1>
        <div class="subtitle">
          <div>智能协同，</div>
          <div>释放创意潜能</div>
        </div>
        <div class="description">一站式云图库管理平台，助力团队高效协作，激发无限创意</div>
        <div class="features">
          <div class="feature-item">
            <el-icon><UserFilled /></el-icon>
            <span>团队协作，共享资源</span>
          </div>
          <div class="feature-item">
            <el-icon><Lock /></el-icon>
            <span>安全加密，数据保护</span>
          </div>
          <div class="feature-item">
            <el-icon><Promotion /></el-icon>
            <span>高效检索，提升效率</span>
          </div>
          <div class="feature-item">
            <el-icon><Service /></el-icon>
            <span>AI助力，智能识别</span>
          </div>
        </div>
      </div>
    </div>
    <div class="form-container">
      <!-- 登录表单 -->
      <div v-if="isLogin">
        <div class="form-header">
          <h2>登录</h2>
          <div class="register-link">
            还没有账号？<el-link type="primary" @click="toggleForm">立即注册</el-link>
          </div>
        </div>
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
          <el-form-item prop="account">
            <el-input
              v-model="loginForm.userAccount"
              placeholder="请输入手机号或邮箱"
              prefix-icon="User"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.userPassword"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          <el-button type="primary" class="login-button" @click="handleLogin">登录</el-button>
        </el-form>
      </div>
      <!-- 注册表单 -->
      <div v-else>
        <div class="form-header">
          <h2>注册</h2>
          <div class="register-link">
            已有账号？<el-link type="primary" @click="toggleForm">返回登录</el-link>
          </div>
        </div>
        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          class="login-form"
        >
          <el-form-item prop="account">
            <el-input
              v-model="registerForm.account"
              placeholder="请输入手机号或邮箱"
              prefix-icon="User"
            />
          </el-form-item>
          <el-form-item prop="verificationCode">
            <div style="display: flex; width: 100%">
              <el-input
                v-model="registerForm.verifyCode"
                placeholder="请输入验证码"
                prefix-icon="Key"
              />
              <el-button style="margin-left: 8px" @click="getCode" :disabled="countDown > 0">{{
                countDown > 0 ? countDown + 's后重新获取' : '获取验证码'
              }}</el-button>
            </div>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请设置6-20位密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          <el-form-item prop="checkPassword">
            <el-input
              v-model="registerForm.checkPassword"
              type="password"
              placeholder="请再次输入密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          <el-button type="primary" class="login-button" @click="handleRegister">注册</el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
import { sendCodeAPI } from '@/api/codeAPI'
import { phoneRegisterAPI, emailRegisterAPI } from '@/api/userAPI'

const router = useRouter()
const userStore = useUserStore()

//  切换登录和注册表单
const isLogin = ref(true)

//验证码倒计时
const countDown = ref(0)
const countDownTimer = ref(null)
const countDownStart = () => {
  countDown.value = 60
  countDownTimer.value = setInterval(() => {
    if (countDown.value > 0) {
      countDown.value--
    } else {
      clearInterval(countDownTimer.value)
      countDown.value = 0
      countDownTimer.value = null
    }
  }, 1000)
}

const loginFormRef = ref(null)
const loginForm = reactive({
  userAccount: '',
  userPassword: '',
})

const loginRules = {
  userAccount: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
  ],
}

const registerFormRef = ref(null)
const registerForm = reactive({
  account: '',
  password: '',
  checkPassword: '',
  verifyCode: '',
})

//判断是否是手机号或邮箱
const isPhoneOrEmail = (value) => {
  const phoneRegex = /^1[3-9]\d{9}$/
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (phoneRegex.test(value)) {
    return 'phone'
  } else if (emailRegex.test(value)) {
    return 'email'
  }
  return false
}

const registerRules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!isPhoneOrEmail(value)) {
          callback(new Error('请输入有效的手机号或邮箱'))
        } else {
          callback()
        }
      },
    },
  ],
  verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20位', trigger: 'blur' },
  ],
  checkPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
    },
  ],
}

const toggleForm = () => {
  isLogin.value = !isLogin.value
  // 重置表单
  if (isLogin.value) {
    registerFormRef.value?.resetFields()
  } else {
    loginFormRef.value?.resetFields()
  }
}

//获取验证码
const getCode = async () => {
  await sendCodeAPI({ userIdentifier: registerForm.account, businessType: 'REGISTER' })
    .then(() => {
      ElMessage.success('验证码已发送，请注意查收')
      countDownStart()
    })
    .catch((error) => {
      ElMessage.error(error.message || '获取验证码失败，请稍后再试')
    })
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  await loginFormRef.value.validate((valid, fields) => {
    if (valid) {
      userStore
        .login({
          userAccount: loginForm.userAccount,
          userPassword: loginForm.userPassword,
        })
        .then(() => {
          ElMessage.success('登录成功')
          // 登录成功后可以跳转到首页或其他页面
          router.push({ name: 'Home' })
        })
        .catch((error) => {
          ElMessage.error(error.message || '登录失败，请检查账号或密码')
        })
    } else {
      console.log('验证失败', fields)
    }
  })
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  await registerFormRef.value.validate((valid, fields) => {
    if (valid) {
      const userIdentifier = isPhoneOrEmail(registerForm.account)
      if (userIdentifier === 'phone') {
        phoneRegisterAPI({
          phone: registerForm.account,
          password: registerForm.password,
          checkPassword: registerForm.checkPassword,
          verifyCode: registerForm.verifyCode,
        })
          .then(() => {
            ElMessage.success('注册成功')
            toggleForm() // 注册成功后切换回登录
          })
          .catch((error) => {
            ElMessage.error(error.message || '注册失败，请稍后再试')
          })
      } else if (userIdentifier === 'email') {
        emailRegisterAPI({
          email: registerForm.account,
          password: registerForm.password,
          checkPassword: registerForm.checkPassword,
          verifyCode: registerForm.verifyCode,
        })
          .then(() => {
            ElMessage.success('注册成功')
            toggleForm() // 注册成功后切换回登录
          })
          .catch((error) => {
            ElMessage.error(error.message || '注册失败，请稍后再试')
          })
      }
    } else {
      console.log('验证失败', fields)
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  min-height: 100vh;
  background: #f5f7fa;
}

@media screen and (max-width: 768px) {
  .login-container {
    flex-direction: column;
  }
}

.login-card {
  flex: 3;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #d05fdc 0%, #125ed8 100%);
  padding: 40px;
}

.login-header {
  color: white;
  max-width: 480px;
}

.logo {
  width: 48px;
  height: 48px;
}

.title {
  font-size: 24px;
  margin: 16px 0;
  display: flex;
  gap: 8px;
}

.subtitle {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 16px;
}

.description {
  font-size: 14px;
  opacity: 0.8;
  margin-bottom: 32px;
}

.features {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-container {
  flex: 4;
  padding: 40px;
  background: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.form-container > div {
  width: 100%;
  max-width: 400px;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
}

.form-header h2 {
  font-size: 24px;
  color: #1f2937;
  margin: 0;
}

.login-form {
  width: 100%;
}

.login-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}
</style>
